package com.yoki.cloud.common.code.db.builder;

import com.yoki.cloud.common.code.db.property.DBTableProperty;

import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通过数据库链接，获取数据库信息，并转换为java bean类
 * Created by SKY on 2017/6/26.
 */
public class DBTableBuilder {

    private static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private Connection connection;

    public DBTableBuilder(Connection connection) {
        this.connection = connection;
    }

    /**
     * 获取数据库表列表
     *
     * @return
     */
    public List<DBTableProperty> buildTableList() {
        List<DBTableProperty> list = new ArrayList<>();
        try {
            String currentCatalog = connection.getCatalog();
            ResultSet resultSet = connection.getMetaData().getTables(currentCatalog, null, null, new String[]{"TABLE"});
            DBColumnBuilder DBColumnBuilder = new DBColumnBuilder(connection);
            int count = 0;
            while (resultSet.next()) {
                count++;
                DBTableProperty table = new DBTableProperty();
                table.setTableCat(resultSet.getString(1));
                table.setTableSchema(resultSet.getString(2));
                table.setTableName(resultSet.getString(3));
                table.setTableType(resultSet.getString(4));
                table.setRemarks(resultSet.getString(5));

                /*table.setTypeCatalog(resultSet.getString(6));
                table.setTypeSchema(resultSet.getString(7));
                table.setTypeName(resultSet.getString(8));
                table.setSelfReferencingColName(resultSet.getString(9));
                table.setRefGeneration(resultSet.getString(10));*/

                long startMillis = System.currentTimeMillis();
                table.setDBColumnPropertyList(DBColumnBuilder.buildColumnList(table.getTableName()));
                list.add(table);

                String sdfTime = SDF.format(new Date());
                System.out.println("\033[0m");
                System.out.print("\033[34m" + sdfTime);
                System.out.print("\033[33m" + "  Find [" + count + "] table :  ");
                System.out.print("\033[35m" + table.getTableName());
                System.out.print("\033[33m" + " ; BuildColumn Cost Time :" + (System.currentTimeMillis() - startMillis) + "ms!");
                System.out.print("\033[0m");
            }
            resultSet.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


}
